<?php 

namespace pmvc\mvc;

use pmvc\log\Log;

use Exception;

/**
 * A class for chaining a request through filters.
 *
 */
class RequestChain {

	private $filters 		= Array();
	private $currentFilter	= -1;

	/**
	 * Adds a {@link RequestFilter} to the chain.
	 * @param RequestFilter $requestFilter
	 */
	public function addFilter(RequestFilter $requestFilter) {
		if ($this->currentFilter!=-1) {
			throw new Exception("RequestChain is already started");
		}
		$this->filters[] = $requestFilter;
	}

	/**
	 * Runs the next {@link RequestFilter} in the chain.
	 * @param Request $request
	 * @param Response $response
	 */
	public function next(Request $request, Response $response) {
		$this->currentFilter++;
		if ($this->currentFilter>=count($this->filters)) {
			return;
		} else {
			$filter = $this->filters[$this->currentFilter];
			Log::trace(__CLASS__, "Executing RequestFilter: {0}", get_class($filter));
			$filter->handleRequest($this, $request, $response);
		}
	}
	
}

?>